package in.muton.edushare.poll.questions;

import in.muton.edushare.pages.EduShareBasePage;

import java.util.List;

import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.vo.Answers;
import com.edushare.common.vo.PollQuestions;

public class RatingQuestion extends QuestionBase {

	public RatingQuestion(String id, IModel<PollQuestions> model,
			EduShareBasePage page, final boolean preview, final boolean editMode) {
		super(id, model, page, preview, editMode);
		add(JavascriptPackageResource.getHeaderContribution(
				RatingQuestion.class, "questions.js"));
		retrieveValues();
		add(new HiddenField<Integer>("rating", new PropertyModel<Integer>(this,
				"rating")));
	}

	public void setRating(Integer rating) {
		this.rating = rating;
	}

	public Integer getRating() {
		return rating;
	}

	private Integer rating = new Integer(10);
	private static final long serialVersionUID = 1717166961602966485L;

	@Override
	public boolean retrieveValues() {
		UserPollDAO upDAO = new UserPollDAO(getORMInterface());
		List<Answers> ansList = upDAO.getAnswerList(getLoggedInUser(),
				getQuestionModel().getObject());
		if (ansList.size() < 1)
			return false;
		setRating(ansList.get(0).getAnswer());
		return true;
	}

	@Override
	public boolean save(boolean draft) {
		if (isPreview() || isEditMode() || (!draft && !verify()))
			return false;
		UserPollDAO uPDao = new UserPollDAO(getORMInterface());
		uPDao.setAnswer(getLoggedInUser(), getQuestionModel().getObject(),
				getRating());
		return true;
	}

	@Override
	public boolean verify() {
		return rating >= 1 && rating <= 10;
	}

	@Override
	public void clear() {
		new UserPollDAO(getORMInterface()).clearAnswers(getLoggedInUser(),
				getQuestionModel().getObject());
		setRating(5);
	}
}
